<template>
  <el-dialog width="80%" :visible="visible" :modal-append-to-body="true" @close="doClose">
    <el-container>
        <el-aside width="20%" style="background: none">
        <!--     分类选择     -->
        <el-row :gutter="20">
          <el-col :span="18">
            <el-input
              style="width: 100%"
              placeholder="过滤"
              v-model="filterText">
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button icon="el-icon-refresh" size="mini" @click="getCategories"></el-button>
          </el-col>
        </el-row>
        <el-tree
          @current-change="changCategory"
          class="filter-tree"
          :data="categories"
          :props="treeProps"
          :filter-node-method="filterNode"
          ref="tree">
        </el-tree>
      </el-aside>
      <el-main style="padding: 8px">
        <!--     查询表单     -->
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
          <el-form-item label="渠道" prop="customerChannel" :rules="[{ required: true, message: '请选择渠道', trigger: 'blur' }]" v-if="showChannel">
            <el-select 
              v-model="customerChannel"
              placeholder="请选择渠道"
              size="small" 
              style="width: 100%;">
              <el-option
                v-for="dict in customerChannelOptions"
                :key="parseInt(dict.dictValue)"
                :label="dict.dictLabel"
                :value="parseInt(dict.dictValue)"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品条码" prop="barcode">
            <el-input
              v-model="queryParams.barcode"
              placeholder="请输入商品条码"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="商品名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入商品名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-form>
        <right-toolbar :showSearch.sync="showSearch"  @handleQuery="handleQuery" @resetQuery="resetQuery"></right-toolbar>
        <!--    商品列表      -->
        <el-table
          class="selection-none"
          max-height="350"
          :data="goodsList"
          ref="table"
          v-loading="loading"
          :row-key="getRowKeys"
          @selection-change="handleSelectionChange"
          style="width: 100%">
          <el-table-column 
            type="selection" 
            width="45" 
            :reserve-selection="true"
            align="center">
          </el-table-column>
          <!-- <el-table-column  width="35">
            <template slot-scope="scope">
              <el-radio :label="scope.row.id" v-model="id" @change="rowClick">
                {{''}}
              </el-radio>
            </template>
          </el-table-column> -->
          <el-table-column
            prop="barcode"
            label="商品条码"
            align="center"
            width="200">
          </el-table-column>
          <el-table-column
            prop="name"
            label="商品名称"
            align="center"
            min-width="300">
          </el-table-column>
          <el-table-column
            prop="categoryName"
            label="分类"
            align="center"
            width="120">
          </el-table-column>
          <el-table-column
            prop="brandName"
            label="品牌"
            align="center"
            width="120">
          </el-table-column>
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
        <el-row style="margin-top: 40px">
          <el-col align="right">
            <el-button @click="doClose">取消</el-button>
            <el-button type="primary" @click="confirmGoods">确定</el-button>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
  </el-dialog>
</template>

<script>
  import {listCategory} from "@/api/goods/category";
  import {listGoods} from "@/api/goods/goods";

  export default {
    name: "GoodsSelector",
    props: {
      visible: Boolean,
      supplierId: null,
      showChannel: false
    },
    data() {
      return {
        filterText: '',
        categories: [],
        treeProps: {
          children: 'children',
          label: 'name'
        },
        total: 0,
        customerChannel: null,
        customerChannelOptions: [],
        // id: null,
        goodsList: [],
        loading: false,
        queryParams: {},
        showSearch: true,
        //本次选中
        curRows: []
      }
    },
    computed: {
      /* isSelected () {
        return this.curRow != null
      } */
    },
    watch: {
      visible: function (val) {
        if(val) {
          this.reset();
          if (!this.categories || !this.categories.length)
            this.getCategories();
          this.getList();
          if (this.showChannel) {
            this.getDicts("goods_monitor_customer_channel").then(response => {
              this.customerChannelOptions = response.data;
            });
          }
        }
      },
      filterText(val) {
        this.$refs.tree.filter(val);
      }
    },
    methods: {
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.curRows = selection;
      },
      getRowKeys(row) {
        return row.goodsId
      },
      changCategory (cur) {
        this.queryParams.categoryId = cur.id;
        this.getList();
      },
      getCategories () {
        this.filterText = '';
        listCategory({}).then(response => {
          // 避免改变源数据，建议克隆（此处浅克隆）
          const arrayCopy = response.data.map(item => Object.assign({}, item));

          // 第一步，将数组根据parentId进行分组，并以parentId为key扁平保存，同时找到根节点
          const obj = {};
          arrayCopy.forEach(item => {
            if (!obj[`${item.parentId}`]) {
              obj[`${item.parentId}`] = []
            }
            obj[`${item.parentId}`].push(item)
          });

          // 第二步，再次遍历数组，挂载自己的子节点
          arrayCopy.forEach(item => {
            if (obj[`${item.id}`]) {
              item.children = obj[`${item.id}`]
            }
          });
          this.categories = [{name:'全部分类'},...obj['0']];
        });
      },
      filterNode(value,data) {
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
      },
      reset () {
        this.resetQuery();
        this.curRows = [];
        this.total = 0;
        this.showSearch = true;
        this.goodsList = [];
        this.customerChannel = null;
        // this.categories = [];
      },
      handleQuery(){
        this.queryParams.pageNum = 1;
        this.getList();
      },
      getList() {
        this.loading = true;
        if(this.supplierId){
          this.queryParams.supplierId = this.supplierId;
        }
        let queryParams = {...this.queryParams};
        listGoods(queryParams).then(response => {
          this.total = response.total;
          response.data = response.data.map(item => {
            return {
            ...item,
            goodsId: item.id,
            goodsName: item.name,
            goodsCode: item.code,
            goodsBarcode: item.barcode,
            }
          })
          this.goodsList = response.data;
          this.loading = false;
        }).catch(reason => {
          this.loading = false;
        });
      },
      resetQuery() {
        this.queryParams = {
          pageSize: 20,
          pageNum: 1
        };
        this.handleQuery();
      },
      confirmGoods () {
        if (this.showChannel) {
          if (!this.customerChannel) {
            this.msgError("请选择渠道!");
            return;
          }
          this.$emit('selected', {customerChannel: this.customerChannel, goodsList: this.curRows});
        } else {
          this.$emit('selected', this.curRows);
        }
        this.doClose()
      },
      doClose () {
        this.$emit('update:visible',false);
        this.$refs.table.clearSelection();
      }
    }
  }
</script>

<style>
  .selection-none *::-moz-selection {
    background: transparent;
    border-color: transparent;
    color: #000000;
  }

  .selection-none *::selection {
    background: transparent;
    border-color: transparent;
    color: #000000;
  }

</style>
